package nid.gallery.view 
{
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.events.TimerEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundLoaderContext;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	import nid.gallery.IView;
	/**
	 * ...
	 * @author Nidin P Vinayakan
	 */
	public class AudioView extends Sprite implements IView
	{
		private var bg:Shape;
		
		public var sound:Sound;
		public var soundChannel:SoundChannel;
		public var volume:Number = 0;
		
		public function AudioView() 
		{
			soundChannel = new SoundChannel();
			configUI();
		}
		
		private function configUI():void 
		{
			bg = new Shape();
			bg.graphics.beginFill(0xCCCCCC);
			bg.graphics.drawRect(0, 0, 300, 90);
			bg.graphics.endFill();
			addChild(bg);
		}
		public function align():void
		{
			bg.x = stage.stageWidth / 2 - bg.width / 2;
			bg.y = (stage.stageHeight - 70) / 2 - bg.height / 2;
		}
		public function clear():void
		{
			var timer:Timer = new Timer(25, 25);
			timer.addEventListener(TimerEvent.TIMER, fade);
			timer.addEventListener(TimerEvent.TIMER_COMPLETE, stop);
			timer.start();
			function fade(e:TimerEvent):void
			{
				soundChannel.soundTransform = new SoundTransform((25 - timer.currentCount) / 25);
			}
		}
		
		private function stop(e:Event=null):void 
		{
			if (e.target is Timer)
			{
				var timer:Timer = Timer(e.target)
				 timer = null;
			}
			soundChannel.stop();
		}
		
		public function push(media:XML):void
		{
			clearSound();
			align();
			
			sound = new Sound();
			sound.addEventListener(Event.COMPLETE, onDownloadComplete);
			sound.addEventListener(ProgressEvent.PROGRESS, onProgress);
			sound.load(new URLRequest(media.@src), new SoundLoaderContext(1000, true));
			soundChannel = sound.play();
			soundChannel.soundTransform = new SoundTransform(0);
			
			var timer:Timer = new Timer(25, 25);
			timer.addEventListener(TimerEvent.TIMER, fade);
			timer.start();
			
			function fade(e:TimerEvent):void
			{
				soundChannel.soundTransform = new SoundTransform(timer.currentCount / 25);
			}
		}
		
		private function onDownloadComplete(e:Event):void 
		{
			
		}
		
		private function onProgress(e:ProgressEvent):void 
		{
			
		}
		
		private function clearSound():void 
		{
			if (soundChannel != null) 
			{ 
				soundChannel.stop(); 
				soundChannel = null; 
				soundChannel = new SoundChannel(); 
			}
			if (sound != null) { sound = null; }
		}
		
	}

}